package com.xiaoc.bulldozer.controller;

import com.xc.framework.cache.manager.CacheManager;
import com.xiaoc.bulldozer.common.dto.MessageDto;
import com.xiaoc.bulldozer.common.service.AccountService;
import com.xiaoc.bulldozer.common.service.SmtpMessageService;
import com.xiaoc.bulldozer.common.service.cache.CommonConfigCacheService;
import org.apache.commons.collections.MapUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping(value = "/smtp")
public class SMTPMessageController extends BulldozerFrontBaseController {

    public static final Logger logger = LoggerFactory.getLogger(SMTPMessageController.class);

    @Resource(name = "smtpMessageService")
    private SmtpMessageService smtpMessageService;
    
    @Resource(name = "accountService")
    private AccountService accountService;
    
    @Resource(name = "commonConfigService")
    private CommonConfigCacheService commonConfigService;

    @Resource(name = "remoteCacheManager")
    private CacheManager remoteCacheManager;
    /**
     * 发送验证码
     */
    @PostMapping("/sendVerifyCode")
    public ModelAndView sendVerifyCode(@RequestBody MessageDto messageDto) {
        smtpMessageService.sendVerifyCode(messageDto.getPhoneNumber(),messageDto.getType());
        return jsonSucess();
    }

    @Resource(name = "closeableHttpClient")
    private CloseableHttpClient closeableHttpClient;

    /**
     * 将map集合的键值对转化成：key1=value1&key2=value2 的形式
     *
     * @param parameterMap 需要转化的键值对集合
     * @return 字符串
     */
    public static String convertStringParamter(Map parameterMap) {

        StringBuffer parameterBuffer = new StringBuffer();
        if (MapUtils.isNotEmpty(parameterMap)) {

            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            Object value = null;

            while (iterator.hasNext()) {

                key = (String) iterator.next();
                if (parameterMap.get(key) != null) {
                    value = parameterMap.get(key);
                } else {
                    value = "";
                }

                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }

        return parameterBuffer.toString();
    }

}
